package cn.kgc.springboot.vue.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 课工场
 * @date 2024/12/19
 * @description
 */
@Component
public class JWTUtil {

    // token的生命周期
    @Value("${jwt.timeout}")
    private Integer expireNumber;
    // secret
    @Value("${jwt.secret}")
    private String secret;

    private Map<String, Object> header;

    public JWTUtil() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "Jwt");
        this.header = map;
    }

    // 生成token
    public String createToken(String key, Map<String, Object> payload) {

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, expireNumber);

        return JWT.create()
                .withHeader(header)
                .withClaim(key, payload)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
    }


    // 校验token
    public void verifyToken(String token){
        JWT.require(Algorithm.HMAC256(secret))
                .build()
                .verify(token);
    }

    // 解析token
    public Map<String,Object>  analyzingToken(String key , String token){
       return  JWT.decode(token).getClaim(key).asMap();
    }

}
